package com.jnu.myfirstapplication.data;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HttpDataLoader {
    //获取网页html源码
    public static String getHttpData(String path) throws Exception{
        URL url = new URL(path);
        HttpURLConnection conn=(HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(5000);
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        try{
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
                BufferedReader reader=new BufferedReader(inputStreamReader);
                String tempLine= null;
                StringBuffer resultBuffer=new StringBuffer();
                while ((tempLine=reader.readLine())!=null){
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
                return resultBuffer.toString();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public List<ShopLocation> ParseJsonData(String JsonText){
        List<ShopLocation> locations=new ArrayList<>();
        try{
            JSONObject root=new JSONObject(JsonText);
            JSONArray shops = root.getJSONArray("shops");
            for(int i=0;i<shops.length();i++){
                JSONObject shop=shops.getJSONObject(i);
                ShopLocation shopLocation=new ShopLocation();
                shopLocation.setName(shop.getString("name"));
                shopLocation.setLongitude(shop.getDouble("longitude"));
                shopLocation.setLatitude(shop.getDouble("latitude"));
                shopLocation.setMemo(shop.getString("memo"));
                locations.add(shopLocation);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return locations;
    }
}
